<?php
/*
Extension Name: Discussion Expiration
Extension Url: N/A
Description: Auto close discussions after a specific expiration date.
Version: 1.0.6
Author: Ziyad (MySchizoBuddy) Saeed
Author Url: N/A
*/

// Discussion Expiration Path
if (!defined('DISCUSSIONEXPIRATION_ROOT')) define('DISCUSSIONEXPIRATION_ROOT', dirname(__FILE__).'/');
$Configuration["DISCUSSIONEXPIRATION_PATH"] = 'extensions/DiscussionExpiration/';


 //Define Global variables
global $Context, $Configuration;

// Discussion Expiration Preferences
if( !array_key_exists('DISCUSSIONEXPIRATION_CATEGORIES', $Configuration)) {AddConfigurationSetting($Context, 'DISCUSSIONEXPIRATION_CATEGORIES', '');}
if( !array_key_exists('DISCUSSIONEXPIRATION_LASTCHECK', $Configuration)) {AddConfigurationSetting($Context, 'DISCUSSIONEXPIRATION_LASTCHECK', time());}

// Discussion Expiration Database
if (!array_key_exists('DISCUSSIONEXPIRATION', $Configuration)) {
    	$Errors = 0;
	$query = "SHOW COLUMNS FROM ".$Configuration['DATABASE_TABLE_PREFIX']."Discussion LIKE `DateExpire` ";
	$result = mysql_query($query);
        if (!$result) {
		$query = "ALTER TABLE `".$Configuration['DATABASE_TABLE_PREFIX']."Discussion` ADD `DateExpire` date NOT NULL default '0000-00-00';";
                if (!mysql_query($query)) $Errors = 1;
        }

        if ($Errors == 0) {
            	AddConfigurationSetting($Context, 'DISCUSSIONEXPIRATION', '1');
        	$Structure = "// Discussions Table Structure
\$DatabaseColumns['Discussion']['DateExpire'] = 'DateExpire';
";
                if (!AppendToConfigurationFile($Configuration['APPLICATION_PATH'].'conf/database.php', $Structure)) $Errors = 1;
        }
}


//Language files
$Context->SetDefinition('DiscussionExpiresOn', 'Discussion Expires on <small>(optional)</small>');
$Context->SetDefinition('DiscussionExpires', 'Discussion Expiration');
$Context->SetDefinition('DiscussionExpireCategory', 'Select the Categories that you want to have the ability to Expire.');
$Context->SetDefinition('DiscussionExpiresList', 'Discussion Expiration List');
$Context->SetDefinition('DiscussionExpiresListNotes', 'Below is a list of open discussions with their respective expiration dates.');
$Context->SetDefinition('DiscussionExpireRoles', 'Discussion Expiration exclusion role');
$Context->SetDefinition('DiscussionExpireRolesNote', 'Select the roles that will be allowed to expire any discussion in any category. The settings above do not apply to these selected roles.');
$Context->SetDefinition('ErrDiscussionExpiresList', 'There are no <u>open</u> discussions pending expiration.');
$Context->SetDefinition('ErrWrongDate', 'You entered "'.ForceIncomingString('DateExpire', '').'". This date is not valid! You must enter date greater than today\'s date "'.date("m/d/Y").'". Use the provided Date Picker or enter date like '.date("m/d/Y", strtotime("next week")).' or "next week" or "this thursday"');
$Context->SetDefinition('DateType', 'Use the provided Date picker or enter date like '.date("m/d/Y", strtotime("next week")).' or "next week" or "this thursday"');
$Context->SetDefinition('DiscussionExpiresError', 'Error Occured. Discussions were not closed');
$Context->SetDefinition('PERMISSION_DISCUSSION_EXPIRATION_NOTRESTRICTED', 'Discussion expiration <u>not</u> restricted to categories');

//Role Permissions
$Context->Configuration['PERMISSION_DISCUSSION_EXPIRATION_NOTRESTRICTED'] = '0';

// Check and Expire Discussion that have passed their expiration date
if($Context->SelfUrl == 'index.php') {

    if (time() > $Context->Configuration["DISCUSSIONEXPIRATION_LASTCHECK"] + 86400) {
        include(DISCUSSIONEXPIRATION_ROOT . 'library/Function.DiscussionExpiration.php');

        $Context->Configuration["DISCUSSIONEXPIRATION_LASTCHECK"] = time();
        $Context->AddToDelegate('DiscussionGrid', 'PostRender', 'CloseExpiredDiscussions');
    }
}

//Add the Date field and calendar in the discussion form
if($Context->SelfUrl == 'post.php' && $Context->Session->User->RoleID > 0) {
    // Libraries
    include(DISCUSSIONEXPIRATION_ROOT . 'library/Function.DiscussionExpiration.php');

    //Add all these js files to make that Calender work
    $Head->AddScript( $Configuration["DISCUSSIONEXPIRATION_PATH"].'js/date.js');
    $Head->AddScript( $Configuration["DISCUSSIONEXPIRATION_PATH"].'js/dimensions.js');
    $Head->AddScript( $Configuration["DISCUSSIONEXPIRATION_PATH"].'js/jquery.datePicker.js');
    $Head->AddString('<script type="text/javascript">
                        var $jde=jQuery.noConflict();
                        Date.format = "mm/dd/yyyy";
                        $jde(document).ready(function(){
                        $jde(".date-pick").datePicker();
                        });
                        </script>');

    if (!$Context->Session->User->Permission('PERMISSION_DISCUSSION_EXPIRATION_NOTRESTRICTED')) { //Check user role permissions
    $Head->AddString('<script type="text/javascript">
                     function Toggle ()
								{
                                    if (document.forms[0].CategoryID) {
                                        var AllowedCategoryString = "'.$Context->Configuration["DISCUSSIONEXPIRATION_CATEGORIES"].'";
                                        var AllowedCategory = AllowedCategoryString.split(",");
                                        for (var i = 0; i < AllowedCategory.length; i++) {
                                            if (AllowedCategory[i] == document.forms[0].CategoryID.options[document.forms[0].CategoryID.selectedIndex].value){
                                                $jde("li.DiscussionExpiration").removeClass("Disable");
                                                break;
                                            }
                                            else  {
                                                $jde("li.DiscussionExpiration").addClass("Disable");
                                            }
                                        }
                                    }
                                }
                            $jde(document).ready(function(){
                                $jde("select.CategorySelect").change(function(){Toggle();});
                                Toggle();
                            });
                                </script>');
    }
    // Add required css
    $Head->AddStylesheet($Configuration["DISCUSSIONEXPIRATION_PATH"] . 'theme/datePicker.css');
    $Head->AddStylesheet($Configuration["DISCUSSIONEXPIRATION_PATH"] . 'theme/style.css');

    // Render the form
    $Context->AddToDelegate('DiscussionForm', 'DiscussionForm_PreCommentRender', 'Render_DateExpireForm');
    $Context->AddToDelegate('DiscussionForm', 'PreSaveDiscussion', 'DiscussionForm_CheckDateExpire');
    $Context->AddToDelegate('DiscussionForm', 'PostSaveDiscussion', 'DiscussionForm_SaveDateExpire');

}
/**
 * Settings Panel. This is where all the forms are generated.
 */
if(($Context->SelfUrl == 'settings.php') && $Context->Session->User->Permission('PERMISSION_CHANGE_APPLICATION_SETTINGS')) {
    include(DISCUSSIONEXPIRATION_ROOT . 'library/PostBackControl.DiscussionExpiration.php');
    $Head->AddStylesheet($Configuration["DISCUSSIONEXPIRATION_PATH"].'theme/style.css');
    $DiscussionExpirationForm = $Context->ObjectFactory->NewContextObject($Context, 'DiscussionExpirationForm');
    $Page->AddRenderControl($DiscussionExpirationForm, $Configuration["CONTROL_POSITION_BODY_ITEM"]);
    $ExtensionOptions = $Context->GetDefinition('Extension Options');
    $Panel->AddList($ExtensionOptions);
    $Panel->AddListItem($ExtensionOptions, $Context->GetDefinition('DiscussionExpires'), GetUrl($Context->Configuration, 'settings.php', '', '', '', '', 'PostBackAction=DiscussionExpiration'));
}

?>
